import asyncHandler from "express-async-handler"
import Order from "../models/order.js"
import Cart from "../models/Cart.js"
import Product from "../models/product.js"

/**
 * 创建订单
 * @router POST /api/order
 * @access private
 */
export const createOrder = asyncHandler(async (req, res) => {
  const {productsItems, shippingAddress, paymentMethod, productsPrice,shippingPrice} = req.body

  if(productsItems && productsItems.length===0) {
    res.status(500)
    throw new Error("没有订单信息")
  } else {
    const order = new Order({
      user: req.user._id,
      productsItems, 
      shippingAddress, 
      paymentMethod, 
      productsPrice,
      shippingPrice, 
      totalPrice: productsPrice+shippingPrice
    })
    const createOrder = await order.save()
    if(createOrder) {
      /* 删除购物车内容 */
      await Cart.remove({user: req.user._id})
      /* 商品库存减少 */
      productsItems.forEach(async(item) => {
        const product = await Product.findById(item.productId)
        product.countInStock -= item.qty
        await product.save()
      })
      res.json({
        success: true,
        msg: '',
        data: createOrder
      })
    } else {
      res.status(500)
      throw new Error("创建订单出错")
    }
  }
})

/**
 * 根据id获取订单
 * @router GET /api/order/:id
 * @access private
 */
export const getOrder = asyncHandler(async (req, res) => {
  const { id } = req.params

  try {
    const order = await Order.findById(id).populate({ path: 'user', select: 'name email' })
    res.json({
      success: true,
      msg: '',
      data: order
    })
  } catch(err) {
    res.status(500)
    throw new Error("id无效")
  }
})

/**
 * 支付订单
 * @router POST /api/order/pay/:id
 * @access private
 */
export const payOrder = asyncHandler(async (req, res) => {
  const { id } = req.params

  try {
    const order = await Order.findById(id).populate({ path: 'user', select: 'name email' })
    if(order) {
      order.isPaid = true
      await order.save()
      res.json({
        success: true,
        msg: '',
        data: order
      })
    }
  } catch(err) {
    res.status(500)
    throw new Error(err)
  }
})

/**
 * 分页获取所有订单
 * @router GET /api/order/paging/list
 * @access admin
 */
export const getAllOrders = asyncHandler(async (req, res) => {
  const {pageNum=1, pageSize=10} = req.query
  const orders = await Order.find({})
    .populate({ path: 'user', select: 'id name' })
    .sort({
      createdAt: 'desc'
    })
    .skip((pageNum-1)*pageSize)
    .limit(pageSize)
  res.json({
    success: true,
    msg: '',
    data: {
      total: await Order.count(),
      pageNum: pageNum,
      pageSize: pageSize,
      orders
    }
  })
})

/**
 * 获取指定用户所有订单
 * @router GET /api/order/paging/list/:id
 * @access private
 */
export const getUserOrders = asyncHandler(async (req, res) => {
  const {pageNum=1, pageSize=10} = req.query

  const orders = await Order.find({user: req.params.id})
    .populate({ path: 'user', select: 'id name' })
    .sort({
      createdAt: 'desc'
    })
    .skip((pageNum-1)*pageSize)
    .limit(pageSize)
  res.json({
    success: true,
    msg: '',
    data:  {
      total: await Order.count({user: req.params.id}),
      pageNum: pageNum,
      pageSize: pageSize,
      orders
    }
  })
})

/**
 * 发货
 * @router POST /api/order/deliver/:id
 * @access admin
 */
 export const deliverOrder = asyncHandler(async (req, res) => {
  const { id } = req.params

  try {
    const order = await Order.findById(id).populate({ path: 'user', select: 'name email' })
    if(order) {
      order.isDelivered = true
      await order.save()
      res.json({
        success: true,
        msg: '',
        data: order
      })
    }
  } catch(err) {
    res.status(500)
    throw new Error(err)
  }
})

/**
 * 收货
 * @router POST /api/order/receive/:id
 * @access admin
 */
 export const receiveOrder = asyncHandler(async (req, res) => {
  const { id } = req.params

  try {
    const order = await Order.findById(id).populate({ path: 'user', select: 'name email' })
    if(order) {
      order.isReceived = true
      await order.save()
      res.json({
        success: true,
        msg: '',
        data: order
      })
    }
  } catch(err) {
    res.status(500)
    throw new Error(err)
  }
})